#pragma once

#include<iostream>
#include<vector>
#include"InetAddr.hpp"
#include"Logger.hpp"

class Route
{
private:
    bool IsExist(const InetAddr& addr)
    {
        for(auto& e : _online_user)
        {
            if(e == addr)
                return true;
        }
        return false;
    }    

    void AddUser(const InetAddr& addr)
    {
        if(IsExist(addr))
            return;
        _online_user.push_back(addr);
    }

    void DeleteUser(const std::string& message, const InetAddr& addr)
    {
        if(message == "QUIT")
        {
            auto it = _online_user.begin();
            while(it != _online_user.end())
            {
                if(*it == addr)
                {
                    _online_user.erase(it);
                    break;
                }
            }
        }
    }

    void SendMessageToAll(int socket_fd, std::string& message)
    {
        for(auto& e : _online_user)
        {
            LOG(LogLevel::DEBUG) << "route [" << message << "] to " << e.ToString();
            std::string info = e.ToString() + "# ";
            info += message;
            sendto(socket_fd, info.c_str(), info.size(), 0, e.Addr(), e.Len());
        }
    }

public:
    void RouteMessageToAll(int socket_fd, std::string& message, InetAddr& addr)
    {
        AddUser(addr);
        SendMessageToAll(socket_fd, message);
        DeleteUser(message, addr);
    }

private:
    std::vector<InetAddr> _online_user;
};